package com.marketingexpert.service.snsmgnt.sina;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import weibo4j.Count;
import weibo4j.Emotion;
import weibo4j.Paging;
import weibo4j.Query;
import weibo4j.Status;
import weibo4j.User;
import weibo4j.WeiboException;

import com.marketingexpert.config.Configuration;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.snsmgnt.AccessToken;
import com.marketingexpert.service.snsmgnt.RequestToken;
import com.marketingexpert.service.snsmgnt.SnsService;
import com.marketingexpert.service.snsmgnt.sina.wei4j.SinaWeibo_;
import com.marketingexpert.util.ContextHolder;
import com.marketingexpert.util.Resources;
import com.marketingexpert.util.WebUtils;

public class SinaWeibo implements SnsService {

	private static Logger logger = Logger.getLogger(SinaWeibo.class);

	private static final String APP_KEY = "2703816706"; //$NON-NLS-1$
	private static final String APP_SECRET = "4ab4b17102fe08f77035232758595714"; //$NON-NLS-1$

	private SinaWeibo_ weibo = null;

	private static Configuration configuration;

	private static SnsService instance = new SinaWeibo();

	private SinaWeibo() {
		reInitialize();
	}

	public static SnsService getInstance() {
		return instance;
	}

	// 设定 callback_url 获取 request token
	public RequestToken getRequestToken(String backUrl) {
		try {
			return new SinaRequestToken(weibo.getOAuthRequestToken(backUrl));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	// 根据requestToken 以及取得的verifier获取accessToken
	public AccessToken gettAccessToken(RequestToken requestToken,
			String verifier) {
		try {
			AccessToken accessToken = new SinaAccessToken(weibo.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(), verifier));
			return accessToken;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	// ��ݴ���� Access Token �����ݷ���΢��
	public String update(String token, String tokenSec, String content)
			throws MarketingExpertException {
		try {
			weibo.setToken(token, tokenSec);
			Status status = weibo.updateStatus(content);
			return String.valueOf(status.getId());
		} catch (WeiboException e) {
			throw new MarketingExpertException(e.getStatusCode(),e);
		}
	}

	public com.marketingexpert.service.snsmgnt.User getUserDetails(
			String token, String tokenSec, String userId) {
		try {
			weibo.setToken(token, tokenSec);
			weibo4j.User user = weibo.showUser(userId);
			return new SinaUser(user);
		} catch (WeiboException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public void reInitialize() {
		// ׼����Consumer Key��Consumer Secret
		// ��Ӧ������΢��Ӧ�þ������뵽�� App key �� Secret key
		System.setProperty("weibo4j.oauth.consumerKey", APP_KEY); //$NON-NLS-1$
		System.setProperty("weibo4j.oauth.consumerSecret", APP_SECRET); //$NON-NLS-1$
		weibo = new SinaWeibo_();
	}

	public String upload(String token, String tokenSec, String content,
			File image) {
		try {

			weibo.setToken(token, tokenSec);
			content = URLEncoder.encode(content, "UTF-8");
			Status status = weibo.uploadStatus(content, image);
			return String.valueOf(status.getId());
		} catch (WeiboException e) {
			throw new MarketingExpertException(e);
		} catch (UnsupportedEncodingException e) {
			throw new MarketingExpertException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new MarketingExpertException(e);
		}

	}

	public List<com.marketingexpert.service.snsmgnt.User> getFriendsStatuses(
			String token, String tokenSec, String userId, int cousor) {
		List<User> userList = null;
		List<com.marketingexpert.service.snsmgnt.User> uList = new ArrayList<com.marketingexpert.service.snsmgnt.User>();
		weibo.setToken(token, tokenSec);
		try {
			userList = weibo.getFriendsStatuses(cousor);

			for (Iterator<User> it = userList.iterator(); it.hasNext();) {
				com.marketingexpert.service.snsmgnt.sina.SinaUser u = new com.marketingexpert.service.snsmgnt.sina.SinaUser(
						it.next());
				uList.add(u);
			}
			return uList;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	// ��ȡ"�ҹ�ע��"΢������
	public int getUserFriendsCount(String token, String tokenSec, String userId) {
		com.marketingexpert.service.snsmgnt.User user = this.getUserDetails(
				token, tokenSec, userId);
		int friendsCount = user.getFriendsCount();
		return friendsCount;
	}

	// ��ȡ"�ҵķ�˿"����
	public int getMyFollowerCount(String token, String tokenSec, String userId) {
		com.marketingexpert.service.snsmgnt.User user = this.getUserDetails(
				token, tokenSec, userId);
		int followerCount = user.getFollowersCount();
		return followerCount;
	}

	public com.marketingexpert.service.snsmgnt.User destroyFriendship(
			String token, String tokenSec, String destoryUserId) {
		weibo.setToken(token, tokenSec);
		try {
			User u = weibo.destroyFriendshipByUserid(destoryUserId);
			return null;
		} catch (WeiboException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/*
	 * ��ȡ�ҵķ�˿�б�
	 * 
	 * @see
	 * com.marketingexpert.service.snsmgnt.SnsService#getFollowedMeStatues(java
	 * .lang.String, java.lang.String, java.lang.String, int)
	 */
	public List<com.marketingexpert.service.snsmgnt.User> getFollowedMeStatues(
			String token, String tokenSec, String userId, int cursor) {

		List<User> userList = null;

		List<com.marketingexpert.service.snsmgnt.User> uList = new ArrayList<com.marketingexpert.service.snsmgnt.User>();
		weibo.setToken(token, tokenSec);
		try {
			userList = weibo.getFollowersStatuses(cursor);

			for (Iterator<User> it = userList.iterator(); it.hasNext();) {
				com.marketingexpert.service.snsmgnt.sina.SinaUser u = new com.marketingexpert.service.snsmgnt.sina.SinaUser(
						it.next());
				uList.add(u);
			}
			return uList;
		} catch (WeiboException e) {
			throw new MarketingExpertException(e);
		}
	}

	/*
	 * ��ȡ�ҵķ�˿�б�,Json��
	 * 
	 * @see
	 * com.marketingexpert.service.snsmgnt.SnsService#existsFriendship(java.
	 * lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	public Map<String, Object> getMyFollowers(String token, String tokenSec,
			String userId, int cursor) throws MarketingExpertException {

		weibo.setToken(token, tokenSec);
		try {
			JSONObject userList = weibo.getFollowersAsJson(cursor);

			JSONArray users = userList.getJSONArray("users");
			int nextCursor = userList.getInt("next_cursor");

			Map<String, Object> userMap = new HashMap<String, Object>();

			userMap.put("result", users);
			userMap.put("nextCursor", nextCursor);

			return userMap;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	public boolean existsFriendship(String token, String tokenSec, String myId,
			String friendId) {
		weibo.setToken(token, tokenSec);
		boolean existsFriendShip;
		try {
			existsFriendShip = weibo.existsFriendship(myId, friendId);
			return existsFriendShip;
		} catch (WeiboException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public List<Emotion> getEmotions(String type, String language) {
		try {
			return weibo.getEmotions(type, language);
		} catch (WeiboException e) {
			logger.warn(Resources.getString("MessageSinaWeibo1.0"));
			throw new RuntimeException(Resources
					.getString("MessageSinaWeibo1.0"), e);
		}
	}

	/**
	 * ��ȡ�ҵ���ҳ ֱ��ʹ��maxId �Լ�sinceId��ҳ
	 * 
	 * @param token
	 * @param tokenSec
	 * @param page
	 * @param since_id
	 * @param max_id
	 * @return
	 */
	public JSONArray getFriendsTimeline(String token, String tokenSec,
			int page, String since_id, String max_id) {
		try {
			weibo.setToken(token, tokenSec);
			Paging paging = new Paging();
			if (page == 1) {
				paging.setPage(page);
			}
			if (since_id != null) {
				paging.setSinceId(Long.parseLong(since_id));
			}

			if (max_id != null) {
				paging.setMaxId(Long.parseLong(max_id) - 1);
			}

			JSONArray statusTimeline = weibo.getFriendsTimelineAsJson(paging);
			return statusTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getUserTimeline",
					new String[] { "call weibo.getUesrTimeline()",
							"In Sinaweibo line !221" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public JSONArray getUserTimeline(String token, String tokenSec, int page,
			String since_id, String max_id, int baseApp) {
		try {
			weibo.setToken(token, tokenSec);

			Paging paging = new Paging();
			if (page > 0) {
				paging.setPage(page);
			} else {
				paging.setPage(1);
			}
			if (since_id != null) {
				paging.setSinceId(Long.parseLong(since_id));
			}

			if (max_id != null) {
				paging.setMaxId(Long.parseLong(max_id));
			}

			JSONArray statusTimeline = weibo.getUserTimelineAsJson(paging,
					baseApp);
			return statusTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getUserTimeline",
					new String[] { "call weibo.getUesrTimeline()",
							"In Sinaweibo line !255" }), e);
			throw new MarketingExpertException(null, e);
		}

	}

	// ��ȡ�û��ղ��б�
	public JSONArray getFavorites(String accessToken, String secret,
			String pageParam, String maxId) {

		int page = Integer.parseInt(pageParam);

		try {
			weibo.setToken(accessToken, secret);
			Paging paging = new Paging();
			paging.setPage(page);
			JSONArray statusTimeline = weibo.getFavorites(paging);
			return statusTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getFavorites",
					new String[] { "call weibo.getFavorites()",
							"In Sinaweibo line !267" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public String repostWeibo(String sid, String status, int isComment,
			String token, String tokenSec) {
		try {
			status = URLDecoder.decode(status, "UTF-8");

			weibo.setToken(token, tokenSec);

			weibo.repost(sid, status, isComment);
			return Resources.getString("SinaWeibo.repostSuccess");
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.repostFailed"), e);
			throw new MarketingExpertException(null, e);
		} catch (UnsupportedEncodingException e) {
			logger.error(Resources.getString("SinaWeibo.URLEncodeFailed"), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public String updateComment(String token, String tokenSec, String sid,
			String comment, String cid, int withoutMention, int commentOri) {
		try {
			comment = URLDecoder.decode(comment, "UTF-8");
			weibo.updateComment(comment, sid, cid);
			return Resources.getString("SinaWeibo.commentSuccess");
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.repostFailed"), e);
			throw new MarketingExpertException(null, e);
		} catch (UnsupportedEncodingException e) {
			logger.error(Resources.getString("SinaWeibo.URLEncodeFailed"), e);
			throw new MarketingExpertException(null, e);
		}
	}

	/*
	 * ��ȡĳһ��΢���µ�����
	 * 
	 * @see
	 * com.marketingexpert.service.snsmgnt.SnsService#getComments(java.lang.
	 * String)
	 */
	public JSONArray getComments(String sid, String token, String tokenSec) {
		try {
			return weibo.getCommentsAsJson(sid);
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.repostFailed"), e);
			throw new MarketingExpertException(null, e);
		}
	}

	/**
	 * ����΢��
	 */
	public String CommentWeibo(String sid, String comment, int commentOri,
			String cid, String token, String tokenSec) {
		try {
			comment = URLDecoder.decode(comment, "UTF-8");
			weibo.updateComment(comment, sid, cid);
			return Resources.getString("SinaWeibo.commentSuccess");
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.repostFailed"), e);
			throw new MarketingExpertException(null, e);
		} catch (UnsupportedEncodingException e) {
			logger.error(Resources.getString("SinaWeibo.URLEncodeFailed"), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public void createFavorite(String token, String secret, String messageId) {
		try {
			weibo.setToken(token, secret);
			weibo.createFavorite(Long.parseLong(messageId));
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.createFavorite",
					new String[] { "call weibo.createFavorite()",
							"In Sinaweibo line !329" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public void destoryStatus(String token, String secret, String messageId) {
		try {
			weibo.setToken(token, secret);
			weibo.destroyStatus(Long.parseLong(messageId));
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.destoryStatus",
					new String[] { "call weibo.destoryStatus()",
							"In Sinaweibo line !345" }), e);
			throw new MarketingExpertException(null, e);
		}

	}

	public void destoryFavorite(String token, String secret, String messageId) {
		try {
			weibo.setToken(token, secret);
			weibo.destroyFavorite(Long.parseLong(messageId));
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.destoryFavorite",
					new String[] { "call weibo.destoryFavorite()",
							"In Sinaweibo line !362" }), e);
			throw new MarketingExpertException(null, e);
		}

	}

	public JSONArray getRtCtCounts(String token, String tokenSec,
			String messageId) throws MarketingExpertException {
		try {
			JSONArray coutsTimeline = weibo.getRtCtCounts(messageId, APP_KEY);
			return coutsTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getFavorites",
					new String[] { "call weibo.getFavorites()",
							"In Sinaweibo line !267" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public JSONArray getCommentsTimeline(String token, String secret, int page,
			String since_id, String max_id) {
		try {
			weibo.setToken(token, secret);

			Paging paging = new Paging();
			if (page >= 0) {
				paging.setPage(page);
			}
			if (since_id != null) {
				paging.setSinceId(Long.parseLong(since_id));
			}

			if (max_id != null) {
				paging.setMaxId(Long.parseLong(max_id));
			}

			JSONArray commentsTimeline = weibo
					.getCommentsTimelineAsJson(paging);
			return commentsTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getUserTimeline",
					new String[] { "call weibo.getUesrTimeline()",
							"In Sinaweibo line !255" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public JSONArray getTrendTimeline(String token, String secret, int page,
			String since_id, String keyword, String max_id) {
		try {
			weibo.setToken(token, secret);

			Paging paging = new Paging();
			if (page >= 0) {
				paging.setPage(page);
			}
			if (since_id != null) {
				paging.setSinceId(Long.parseLong(since_id) + 1);
			}

			if (max_id != null) {
				paging.setMaxId(Long.parseLong(max_id) - 1);
			}

			JSONArray commentsTimeline = weibo.getTrendTimelineAsJson(paging,
					keyword);
			return commentsTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getUserTimeline",
					new String[] { "call weibo.getUesrTimeline()",
							"In Sinaweibo line !255" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	/**
	 * ��ȡ���ŵĻ���
	 */
	public JSONArray getHotTrendsTimeline(String keyword, Integer baseApp) {
		try {
			reInitialize();
			JSONArray commentsTimeline = weibo.getHotTrendsTimelineAsJson(
					keyword, baseApp, APP_KEY);
			return commentsTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getHotTrendsTimeline",
					new String[] { "call weibo.getHotTrendsTimeline()",
							"In Sinaweibo line !468" }), e);
			throw new MarketingExpertException(e.getMessage(), e);
		}
	}

	/**
	 * ��ȡ@�ᵽ�ҵ�
	 * 
	 * @param token
	 * @param tokenSec
	 * @param page
	 * @param since_id
	 * @param max_id
	 * @return
	 */
	public JSONArray getMentionsTimeline(String token, String tokenSec,
			int page, String since_id, String max_id) {
		try {
			weibo.setToken(token, tokenSec);

			Paging paging = new Paging();
			if (page >= 0) {
				paging.setPage(page);
			}
			if (since_id != null) {
				paging.setSinceId(Long.parseLong(since_id));
			}

			if (max_id != null) {
				paging.setMaxId(Long.parseLong(max_id));
			}

			JSONArray statusTimeline = weibo.getMentionsTimeline(paging);
			return statusTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getMentionsTimeline",
					new String[] { "call weibo.getMentionsTimeline()",
							"In Sinaweibo line !480" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public String reply(String sid, String comment, String cid) {
		try {
			comment = URLDecoder.decode(comment, "UTF-8");
			weibo.reply(sid, cid, comment);
			return Resources.getString("SinaWeibo.replySuccess");
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.repostFailed"), e);
			throw new MarketingExpertException(null, e);
		} catch (UnsupportedEncodingException e) {
			logger.error(Resources.getString("SinaWeibo.URLEncodeFailed"), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public String deleteComment(String sid) {
		try {
			weibo.destroyComment(Long.parseLong(sid));
			return Resources.getString("SinaWeibo.deleteCommentSuccess");
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.repostFailed"), e);
			throw new MarketingExpertException(null, e);
		}
	}

	public JSONArray getDirectMessageTimeline(String token, String secret,
			int page, String since_id, String max_id) {
		try {
			weibo.setToken(token, secret);

			Paging paging = new Paging();
			if (page >= 0) {
				paging.setPage(page);
			}
			if (since_id != null) {
				paging.setSinceId(Long.parseLong(since_id));
			}

			if (max_id != null) {
				paging.setMaxId(Long.parseLong(max_id));
			}

			JSONArray commentsTimeline = weibo
					.getDirectMessageTimelineAsJson(paging);
			return commentsTimeline;
		} catch (WeiboException e) {
			logger.error(Resources.getString("SinaWeibo.getUserTimeline",
					new String[] { "call weibo.getUesrTimeline()",
							"In Sinaweibo line !255" }), e);
			throw new MarketingExpertException(null, e);
		}
	}

	/*
	 * �����Ż���(non-Javadoc)
	 * 
	 * @see
	 * com.marketingexpert.service.snsmgnt.SnsService#getTXtrendTimeline(java
	 * .lang.String, java.lang.String, int, java.lang.String, java.lang.String)
	 */
	@Deprecated
	public Map<String, Object> getTXtrendTimeline(String token,
			String tokenSec, int page, String keyword, String pageInfo) {
		// TODO Auto-generated method stub
		throw new UnsupportedOperationException();
	}

	/*
	 * ��ַ����(non-Javadoc)
	 * 
	 * @see
	 * com.marketingexpert.service.snsmgnt.SnsService#shortUrl(java.lang.String)
	 */
	public String shortUrl(String url) throws MarketingExpertException {
		try {
			String shortUrl = weibo.shortUrl(url, APP_KEY);

			return shortUrl;
		} catch (MarketingExpertException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

	}

	public void sendPrivateMessage(String accessToken, String secret,
			String receiverName, String content) {
		throw new UnsupportedOperationException();
	}

	/**
	 * 从新浪微博查询自动营销的微博素材
	 *  1:遍历所有人的微薄 如果找到一条跟系统设定的最低转发数相同
	 *  2:则取到一条 停止查找
	 *  3:如果找不到 我们就取转发数最多的一条
	 * @param uid 用于查找的微博用户的id列表
	 * @return
	 * @throws MarketingExpertException
	 */	
	public Map<String, Object> getOneTrendMessage(String uids) {
		this.reInitialize();
		configuration = (Configuration) ContextHolder.getBean("configuration");
		List<Status> statuses = null; //一次查询获取的微博
		Status fitStatus = null;
		long retweetNum = 0;   //所有获取的微博的转发次数,用于比较获得转发数最多的微博
		boolean isSearched = false;
		try {			
			String[] uidsArray = uids.split(",");			
			weibo.setSource(APP_KEY);
			Paging page = new Paging();
			page.setPage(1); //取用户第一页的微博
			for(String uid: uidsArray) {
				statuses = weibo.getSpecialUserTimeline(uid, page, APP_KEY, null);				
				for(Status status : statuses) {					
					if (!status.isRetweet()) {
						List<com.marketingexpert.service.snsmgnt.Count> counts = weibo.getCountsByIds(status.getMid());
						if (counts == null || counts.size() <= 0) {
							continue;
						} else if (counts.get(0).getRt() >= configuration.getLeastRt()) { // 此条微博满足要求
							
							if(WebUtils.isToday(status.getCreatedAt())) { //判断是不是当天的微博
								fitStatus = status;
								isSearched = true;
								break;
							} else {
								continue;
							}
							
						} else {  
							if(fitStatus == null || retweetNum < counts.get(0).getRt()) { // 将此条微博缓存下来
								fitStatus = status; 
								retweetNum = counts.get(0).getRt(); 
							}							
						}
					}					
				}				
				if(isSearched) {
					break;
				}				
			}		
			
			Map<String, Object> results = new HashMap<String, Object>();
			results.put("text", fitStatus.getText());
			if (fitStatus.getOriginal_pic() != null && !fitStatus.getOriginal_pic().equals("")) {
				results.put("picture", fitStatus.getOriginal_pic());
			}
			return results;	
		} catch (WeiboException e) {
			logger.error(e);
			throw new MarketingExpertException(e);
		}
	}
	
	/*public Map<String, Object> getOneTrendMessage(String uids) {
		configuration = (Configuration) ContextHolder.getBean("configuration");
		try {
			this.reInitialize();
			weibo.setSource(APP_KEY);
			List<Status> statuses = null;
			List<Status> selectStatus = new ArrayList<Status>();
			Paging page = new Paging();
			
			for (int j = 0; j < 5; j++) { 
				String maxId = null;
				if (statuses != null) {
					maxId = statuses.get(statuses.size() - 1).getMid();
					statuses = null;
				}
				page.setPage(j + 1);

				try {

					statuses = weibo.getSpecialUserTimeline(uid, page, APP_KEY,
							maxId);
					for (Status status : statuses) {
						if (!status.isRetweet()) {
							List<com.marketingexpert.service.snsmgnt.Count> counts = weibo
									.getCountsByIds(status.getMid());
							if (counts == null || counts.size() <= 0) {
								continue;
							}
							if (counts.get(0).getRt() >= configuration
									.getLeastRt()) { // ��ת�������50ʱ,����ӽ��ѡ���list��
								selectStatus.add(status);
							}
						}
					}
					if (selectStatus.size() >= 5) {
						break;
					}
				} catch (MarketingExpertException e) {
					if (j <= 2) {
						continue;
					} else {
						throw e;
					}

				}
			}

			
			
			Status status = selectStatus.get(new Random().nextInt(selectStatus.size()));

			Map<String, Object> results = new HashMap<String, Object>();

			results.put("text", status.getText());

			if (status.getOriginal_pic() != null
					&& !status.getOriginal_pic().equals("")) {
				results.put("picture", status.getOriginal_pic());
			}
			return results;
		} catch (WeiboException e) {
			logger.error(e);
			throw new MarketingExpertException(e);
		}

	}*/

	/**
	 * ����api(Ŀǰ�޷�����)
	 */
	public JSONArray statusSearch(String q, int page, int pageCount,
			int base_app, int filter_ori, boolean needcount) {
		try {

			JSONArray _s = weibo.statussearchAsJson(q, page, pageCount,
					base_app, filter_ori, needcount, APP_KEY);
			return _s;
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException(e);
		}

	}

	/*
	 * ��ȡ�ҵķ�˿,���Լ�û�й�עҪ�ӹ�ע,�������ֻΪ�Զ���ע��job����(����ط����ûᵼ����Ӧ����)
	 */
	public List<com.marketingexpert.service.snsmgnt.User> getMyFollowsSpecial(
			String token, String tokenSec, String userId, int cursor) {

		List<User> userList = null;
		List<com.marketingexpert.service.snsmgnt.User> uList = new ArrayList<com.marketingexpert.service.snsmgnt.User>();

		weibo.setToken(token, tokenSec);
		try {
			
			if(cursor > 0) {
				cursor = cursor * 20;
			}
			
			userList = weibo.getFollowersStatuses(cursor);

			for (Iterator<User> it = userList.iterator(); it.hasNext();) {
				com.marketingexpert.service.snsmgnt.sina.SinaUser u = new com.marketingexpert.service.snsmgnt.sina.SinaUser(
						it.next());
				boolean isFriend = this.existsFriendship(token, tokenSec,
						userId, u.getId());
				u.setMyFollowed(isFriend);
				uList.add(u);
			}
			return uList;
		} catch (WeiboException e) {
			throw new MarketingExpertException(e);
		}
	}

	public boolean createFriendship(String token, String tokenSec, String userId) {
		try {
			weibo.setToken(token, tokenSec);
			weibo.createFriendship(userId);
			return true;
		} catch (WeiboException e) {
			throw new MarketingExpertException(e);
		}
	}

	@Override
	public void logout(String uid) {
		weibo.logout(uid, APP_KEY);
	}

	@Override
	public Map<String, Object> getUserTimelineForPublic(String token,
			String tokenSec, int page, String sinceId, String maxId, int baseApp) {
		return null;
	}

}
